use crossterm::{
    event::{self, Event, KeyCode, KeyEvent},
    terminal::{disable_raw_mode, enable_raw_mode},
    ExecutableCommand,
};
use std::{io, time::Duration};

fn main() -> io::Result<()> {
    // 进入终端原始模式
    enable_raw_mode()?;
    let mut stdout = io::stdout();

    println!("监听中... (按 Q 退出)");
    stdout.flush()?;

    let mut ctrl_pressed = false;
    let mut alt_pressed = false;
    let mut last_key = None;

    loop {
        if event::poll(Duration::from_millis(100))? {
            match event::read()? {
                Event::Key(KeyEvent {
                    code: KeyCode::Char('q'),
                    modifiers: _,
                }) => break, // 按 Q 退出

                Event::Key(KeyEvent {
                    code: KeyCode::Ctrl('c'),
                    modifiers: _,
                }) => {
                    println!("记录 1 (Ctrl+C)");
                }

                Event::Key(KeyEvent {
                    code: KeyCode::F(1),
                    modifiers: _,
                }) => {
                    println!("记录 2 (F1)");
                }

                Event::Key(KeyEvent {
                    code: KeyCode::Esc,
                    modifiers: _,
                }) => {
                    // 处理组合键的释放状态
                    ctrl_pressed = false;
                    alt_pressed = false;
                    last_key = None;
                }

                Event::Key(KeyEvent {
                    code: KeyCode::Ctrl,
                    modifiers: _,
                }) => {
                    ctrl_pressed = true;
                    last_key = None; // 重置最后按键
                }

                Event::Key(KeyEvent {
                    code: KeyCode::Alt,
                    modifiers: _,
                }) => {
                    alt_pressed = true;
                    last_key = None;
                }

                Event::Key(KeyEvent { code, modifiers }) => {
                    // 处理其他组合键逻辑
                    if ctrl_pressed && alt_pressed && code == KeyCode::Delete {
                        println!("记录 3 (Ctrl+Alt+Del)");
                        ctrl_pressed = false;
                        alt_pressed = false;
                    }
                    last_key = Some(code);
                }

                _ => {}
            }
        }

        // 刷新输出缓冲区
        stdout.queue(ExecutableCommand::Reset)?;
        stdout.flush()?;
    }

    // 退出时恢复终端设置
    disable_raw_mode()?;
    Ok(())
}